package cn.lxb.web.starter.template.provider;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * XMLWorkerHelper字库类
 *
 * @author zhoukui
 * @author 54lxb
 * @since 2019-11-20
 */
public class PdfAsianFontProvider extends XMLWorkerFontProvider {

    private String relativeFontPath = "font/simhei.ttf";

    private BigDecimal fontSize;

    public BigDecimal getFontSize() {
        return fontSize;
    }

    public void setFontSize(BigDecimal fontSize) {
        this.fontSize = fontSize;
    }

    public PdfAsianFontProvider() {

    }

    public PdfAsianFontProvider(String relativeFontPath) {
        if (!StringUtils.isEmpty(relativeFontPath)) {
            this.relativeFontPath =  relativeFontPath;
        }
    }

    @Override
    public Font getFont(final String fontName, final String encoding, final boolean embedded, final float size, final int style, final BaseColor color) {
        BaseFont baseFont = getBaseFont(relativeFontPath);
        if (null == baseFont) {
            return super.getFont(fontName, encoding, embedded, size, style, color);
        }
        Font font = new Font(baseFont, size, style, color);
        if (fontSize != null) {
            font.setSize(fontSize.floatValue());
        }
        return font;
    }

    /**
     * 构建 BaseFont
     *
     * @param relativeFontPath 字体路径
     * @return BaseFont OR NULL
     */
    private BaseFont getBaseFont(String relativeFontPath) {
        try {
            ClassPathResource resource = new ClassPathResource(relativeFontPath);
            return BaseFont.createFont(resource.getPath(), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }
}
